$(function(){
	// function initSlider(){
	// 	var starColor=['#ecf0f1','#7f8c8d','#8e44ad','#e67122','#1abc9c','#3498DB','2C3E50'];
	// 	var slider=$("#slider");
	// 	var sliderValue=slider.data('value');
	// 	slider.slider({ value: sliderValue });
	// 	var sliderRange=slider.children('.ui-slider-range');
	// 	var sliderHandle=slider.children('.ui-slider-handle');
	// 	var bgcolor=starColor[sliderValue-1];
	// 	if(bgcolor){
	// 		sliderHandle.css("backgroundColor",bgcolor);
	// 		sliderRange.css("backgroundColor",bgcolor);
	// 	}
	// 	var myrate=$("#myrate");
	// 	slider.on("slidechange",function(event,ui){
	// 		var value=ui.value-1;
	// 		bgcolor=starColor[value];
	// 		sliderHandle.css("backgroundColor",bgcolor);
	// 		sliderRange.css("backgroundColor",bgcolor);
	// 		myrate.text("你的评价："+value);
	// 	});
	// 	slider.on("slidechange",_.debounce(function( event, ui ) {
	// 		var bid=$(this).data('bid');
	// 		var value=ui.value-1;
	//    	if (this.promise_rate && this.promise_rate.state() === 'pending') {
	//       this.promise_rate.abort();
	//     }
	// 		this.promise_rate = $.get("/ajax/rate",{bid:bid,value:value},function(data){


	// 		});
	// 	},1000));


	// }


	// initSlider();
	// setTimeout(function(){
	// 	$("#bookinfo").collapse('hide');
	// },1000)
	(function(window){
		var urlPath = window.location.pathname,urlHash=window.location.hash;
		if(urlPath && urlHash && urlPath.match(/^\/book\/\d+$/)){
			var cid = urlHash.substr(1);
			setTimeout(function(){
				ys.common.viewOneComment(cid);
			},300);
		}
	})(window);

	(function(){




	})();

	function rateInit(rateObj,clickfunc){
		var myrate=$(rateObj);
		var ratelabel = myrate.parent().children(".myratelabel");
		var ratedoms=myrate.children("i"),bid=myrate.data("bid");
		myrate.on("mouseleave",function(){
			var rate=parseInt(myrate.data("rate"));
			if(!rate)rate=0;
			changeRateColor(ratedoms,--rate,"#4d7bd6",ratelabel);
		})
		ratedoms.on("mouseenter",function(){
			var index=$(this).index();
			changeRateColor(ratedoms,index,"#61b100",ratelabel);
		})
		if(clickfunc){
			ratedoms.on("click",function(){
				var index=$(this).index();
				clickfunc(index+1);
			})
		}
	}

	var myrate=$("#myrate");
	if(myrate[0]){
		var ratedoms=myrate.children("i"),bid=myrate.data("bid");
		myrate.on("mouseleave",function(){
			var rate=parseInt(myrate.data("rate"));
			if(!rate)rate=0;
			changeRateColor(ratedoms,--rate,"#4d7bd6");
		})
		ratedoms.on("mouseenter",function(){
			var index=$(this).index();
			changeRateColor(ratedoms,index);
		})
		ratedoms.on("click",function(){
			var index=$(this).index();
			ajaxPromise(function(){
				return $.get("/ajax/rate",{bid:bid,value:index+1},function(data){
					defaultDataHandler(data);
					if(data.rate){
						myrate.data("rate",data.rate);
						var rate=data.rate-1;
						changeRateColor(ratedoms,rate,"#4d7bd6");
					}
	 			});
			})

		})
	}

	function updateRate(rate){
		var myrate=$("#myrate");
		if(myrate[0]){
			var ratedoms=myrate.children("i");
			myrate.data("rate",rate);
			rate--;
			changeRateColor(ratedoms,rate,"#4d7bd6");
		}
	}

	function changeRateColor(doms,index,color,myratelabel){
		if(!myratelabel) var myratelabel=$("#myratelabel");
		var rateLabelArr=["未评分","剧毒","毒草","干粮","粮草","仙草"];
		if(!color)color="#61b100"
		for(var i=0;i<doms.length;i++){
			if(i<=index){
				$(doms[i]).css({color:color})
			}else{
				$(doms[i]).css({color:"#ccc"})
			}
		}
		index++;

		if(myratelabel[0] && rateLabelArr[index]){
			myratelabel.text(rateLabelArr[index]);
		}
	}

	if(typeof ys=="undefined")ys={};
	var SOKK={};
	ys.book=SOKK;

		// 切换书的标签显示
		SOKK.showEditBookTag=function(){
			var booktag=$("#booktag");
			var tags=booktag.data("tags");
			var editbooktag=$("#editbooktag");
			editbooktag.importTags(tags);
			booktag.hide();
			editbooktag.parent().show();
		}
		// 保存书的标签信息
		SOKK.saveBookTag=function(bid){
			var booktag=$("#booktag"),editbooktag=$("#editbooktag");
			var currentTags= editbooktag.currentTags();
			var url="/updatebooktag/"+bid;
			$.ajax({
				url:url,
				type:"post",
				dataType:"json",
				data:{
					tags:currentTags
				},
				success:function(data){
					if(!data){

					}else if(data.tags){
						var htmls=tagsToDom(data.tags);
						booktag.data("tags",data.tags.join(","));
						booktag.html(htmls);
					}
					booktag.show();
					editbooktag.parent().hide();
				},
				error:function(err){

				}

			})

			function tagsToDom(tags){
				var domArr=[];
				for(var i=0;i<tags.length;i++){
						domArr.push(
							'<a class="btn btn-primary" href="/tag/'+tags[i]+'" target="_blank">'+tags[i]+'</a>');
				}
				domArr.push('<a class="btn btn-link" onclick="SOKK.showEditBookTag()">修改或增加标签</a>');
				return domArr.join("");
			}
		}

		SOKK.tobooklist=function(){
			ajaxPromise(function(){
				var url=$("#tobooklist").data("url");
				return $.get(url,function(body){
					defaultDataHandler(body);
					if(body.needlogin || !body.content)return false;

					var Modal=sokkModal({
						title:"加入推书单",
						body:body.content,
						submit:function(obj){
							var data=obj.serialize();
							var options={data:data,url:"/ajax/tobooklist"};
							options.callback=function(data){
								if(data.rate){
									updateRate(data.rate);
								}
								Modal.hide();
							}
							submitForm(options);
						}
					});
					$("#tobooklist_textarea").maxlength();
					var newlistDom=$('<a onclick="ys.common.editBookListModal();" href="javascript:;" class="btn btn-primary extrabtn pull-left">新书单</a>');
					Modal.find(".modal-footer").prepend(newlistDom);
					var exitrate=parseInt($("#myrate").data("rate"));
					if(exitrate){
						$("#booklistrateselect").val(exitrate);
					}
					Modal.show();
					$("#booklistselect").selectpicker();
				})
			},"tobooklist");
		}

		SOKK.editmytag=function(bid){
			ajaxPromise(function(){
				return $.get("/ajax/getmytag",{bid:bid},function(body){
					defaultDataHandler(body);
					if(body.needlogin || !body.content)return false;
					var Modal=sokkModal({
						title:"修改标签",
						body:body.content,
						submit:function(obj){
							var data=obj.serialize();
							var options={data:data,url:"/ajax/editmytag"};
							options.callback=function(data){
								var tags=data.tags.split(" ");
								var newtags=[];
								for(var i=0;i<tags.length;i++){
									newtags.push('<span class="tag">'+tags[i]+'</span>');
								}
								$("#booktagtext").html(newtags.join(""));
								Modal.hide();
							}
							submitForm(options);
						}
					});
					Modal.show();
				})
			},"tobooklist");
		}

		SOKK.addtag=function(obj){
			var text=$(obj).text();
			if(text){
				text=text.trim();
				changeBookTag(text);
			}

		}
		function changeBookTag(text){
			var tagstr=$("#mybooktag").val();
			if(!tagstr)tagstr="";
			var tagArr=tagstr.split(" ");
			var newArr=[],isexit=false;
			for(var i=0;i<tagArr.length;i++){
				if(tagArr[i]===text){
					// isexit=true;
				}else if(tagArr[i]){
					newArr.push(tagArr[i]);
				}
			}
			if(!isexit)newArr.push(text);
			tagstr=newArr.join(" ");
			$("#mybooktag").val(tagstr);
		}

		SOKK.editcategory=function(bid){
			if(!bid)return false;
			if(typeof bid==="string")bid=bid.trim();
			ajaxPromise(function(){
				return $.get("/ajax/getcategory",function(body){
					var content = '<input type="hidden" name="bid" value="'+bid+'">'+body.content;
					var config={content:content};
					config.title="给本书分类";
					config.size="small";
					config.submit=function(){
						var modal=this,form=this.form;
						var data=form.serialize();
						var options={data:data,url:"/ajax/changecategory"};
						options.callback=function(data){
							var booktag=$("#booktagtext").parent();
							if(booktag[0]){
								var categorydom=booktag.children("a.category");
								if(categorydom[0]){
									categorydom.remove();
								}
								var str='<a href="/category/'+data.category+'" class="tag category" style="background-color:#5bc0de;color:#fff">'+data.categoryname+'</a>';
								booktag.prepend(str);
							}else if(data.bids){
								var bids=data.bids.split(",");
								for(var i=0;i<bids.length;i++){
									var xzbook= $("#xzbook_"+bids[i]);
									xzbook.remove();
								}
							}
						}
						submitForm(options);
						this.modal("hide");
					}
					createModal(config).modal("show");
				});
			},"tobooklist");
		}
		SOKK.recaijibook=function(bid){
			bid=parseInt(bid);
			if(!bid)return false;
			ajaxPromise(function(){
				return $.get("/ajax/recaijibook",{bid:bid},function(body){
					defaultDataHandler(body);
					var url=location.href;
					setTimeout(function(){
						location.href=url;
					},500)
				})
			},"tobooklist");
		}

function ajaxModal(){
	ajaxPromise()
	// var options={title:}

}
SOKK.writecontentModal = function(body){

		var config={title:"书评",content:body,footer:false};
		config.submit=function(obj){
			var form=this.form;
			ys.book.writecontent(form);
			this.modal("hide");
		}
		var modal = createModal(config).modal("show");
		rateInit($(".myrate"),function(ratenum){
			var form = modal.form;
			form.find("input[name='rate']").val(ratenum);
			form.submit();
		});
}

SOKK.writecontent=function(obj){
	var form=$(obj);
	var arr=form.serializeArray();
	var extra={};
	for(var i=0;i<arr.length;i++){
		extra[arr[i].name]=arr[i].value;
	}
	if(!extra.content){
		toastr.error("你没有输入内容！");
	}else{
		var config={};
		config.data=form.serialize();
		config.url="/ajax/postcomments";
		config.form=form;
		config.callback=function(data){
			if(data && data.comment){
				var dom=$(data.comment)[0];
				$("#content").masonry().children(":first").after(dom).parent().masonry( 'prepended', dom);
				$("#fastwritecotentinput").val("");
			}else if(data.needModal){
				ys.book.writecontentModal(data.html);
			}
		}
		submitForm(config);
	}
}

SOKK.nextcomment = function(bid,nexttime){
	var btn = $("#next_comment_btn");
	btn.remove();
	var bid = parseInt(bid),nexttime = parseInt(nexttime);
	if(!bid || !nexttime) return;
	$.getJSON("/ajax/nextcomment",{bid:bid,nexttime:nexttime},function(data){
		var contentDom = $("#content");
		contentDom.children("div").removeClass("isnew");
		if(data && data.comment){
			var dom=$(data.comment)
			contentDom.masonry()
  								.append( dom )
  								.masonry( 'appended', dom )
  								// layout
  								.masonry();
			// $("#content").append(data.comment).masonry();
		}

	})
}


		// 增加书的状态

		$(".sokk-readstate-btn").on('click',function(event){
			var readstate=$(this).data('readstate');
			var bid=$(this).data('bid');
			if(readstate!=="wait"){
				changeReadState(bid,readstate);
			}else{
				var body=$("#readstatewait").html();
				createModal({
					title:"养肥本书",
					content:body,
					submit:function(obj){
						var arr=obj.serializeArray();
						var extra={};
						for(var i=0;i<arr.length;i++){
							extra[arr[i].name]=arr[i].value;
						}
						extra.modal=Modal;
						changeReadState(bid,readstate,extra);
						Modal.hide();
					}
				})
				var Modal=sokkModal({
					title:"养肥本书",
					body:body,
					submit:function(obj){
						var arr=obj.serializeArray();
						var extra={};
						for(var i=0;i<arr.length;i++){
							extra[arr[i].name]=arr[i].value;
						}
						extra.modal=Modal;
						changeReadState(bid,readstate,extra);
						Modal.hide();
					}
				});
				Modal.show();

			}
		})



		// 改变书的状态
		function changeReadState(bid,readstate,extra){
     	if (this.promise_readstate && this.promise_readstate.state() === 'pending') {
        this.promise_readstate.abort();
      }
      var data={bid:bid,state:readstate};
      var modal=null;
      if(extra){
      	for(var i in extra){
      		if(extra.hasOwnProperty(i) && i!=="modal") {
						data[i]=extra[i];
					}
      	}
      	if( extra.modal)modal= extra.modal;
      }
			this.promise_readstate=$.get("/ajax/readbookstate",data,function(data){
				defaultDataHandler(data);
				if(data && data.state){
					var readstateBtn=$(".sokk-readstate-btn");
					var rubbishBtn=$("#btn-rubbish");
					for(var i=0;i<readstateBtn.length;i++){
						var dom=$(readstateBtn[i]);
						if(data.state === "rubbish"){
							rubbishBtn.text("取消不看");
						}else{
							rubbishBtn.text("不看本书");
						}
						if(dom.data('readstate')==data.state){
							dom.removeClass("btn-default").addClass("btn-primary");
						}else{
							dom.removeClass("btn-primary").addClass("btn-default");
						}
					}
					if(modal)modal.hide();
				}
			})
		}

		function sokkModal(options){
			var sokkmodal=$("#sokkmodal");
			var modalDialog=sokkmodal.children(".modal-dialog");
			var modalTitle=sokkmodal.find(".modal-title");
			var modalBody=sokkmodal.find(".modal-body");
			var modalForm=sokkmodal.find("form");
			var modalFooter=sokkmodal.find(".modal-footer");
			modalFooter.children("a.extrabtn").remove();
			sokkmodal.modalTitle=modalTitle;
			sokkmodal.modalBody=modalBody;
			sokkmodal.modalForm=modalForm;

			if(options.title)modalTitle.text(options.title);
			if(options.body)modalBody.html(options.body);
			modalDialog.removeClass("modal-lg").removeClass("modal-sm");
			if(options.size){
				switch(options.size){
					case 'large':
						var dialogsize="modal-lg";
						break;
					case 'small':
						var dialogsize="modal-sm";
						break;
					default:
						break;
				}
				if(dialogsize)modalDialog.addClass(dialogsize);
			}

			var scope=options.scope?options.scope:this;
			modalForm.off().on("submit",function(event){
				var obj=$(this);
				options.submit.call(scope,obj);
				return false;
			})

			sokkmodal.show=function(){
				sokkmodal.modal('show');
			}
			sokkmodal.hide=function(){
				sokkmodal.modal('hide');
			}
			return sokkmodal;
		}

})
